/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client.pipeConnector;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.channels.Pipe.SinkChannel;
import java.nio.channels.Pipe.SourceChannel;

/**
 *
 * @author Александр Емельянов (mr.lex91@gmail.com)
 */
public class PipeConnectorBuffered implements IPipe{
    private SinkChannel writer;
    private SourceChannel reader;
    private String part="";
    
    public static IPipe[] createPipe() throws IOException
    {
        PipeConnectorBuffered[] pipeConnector=new PipeConnectorBuffered[2];
        Pipe p1=Pipe.open();
        Pipe p2=Pipe.open();
        pipeConnector[0]=new PipeConnectorBuffered(p1.source(), p2.sink());
        pipeConnector[1]=new PipeConnectorBuffered(p2.source(), p1.sink());
        return pipeConnector;
    }
    
    PipeConnectorBuffered(SourceChannel reader, SinkChannel writer)
    {
        this.reader=reader;
        this.writer=writer;
    }
    @Override
    public String Read()
    {
        int n=1024;
        int i=n;
        ByteBuffer buf1 = ByteBuffer.allocate(n);
        String str=part;
        try {
            while (true)
            {
                if (str.contains("<END>"))
                {
                    if (str.indexOf("<END>")+6<str.length()) part=str.substring(str.indexOf("<END>")+5, str.length());
                    else part="";
                    str=str.substring(0, str.indexOf("<END>"));
                    return str;
                }
                buf1.clear();
                if(i<n) return str;
                i = reader.read(buf1);
                buf1.flip();
                str+=new String(buf1.array(),0,i);
            }
        } catch (IOException ex) {}
        return str;
    }
    @Override
    public void Write(String text)
    {
        ByteBuffer buf = ByteBuffer.allocate(2*text.length()+5);
        buf.clear();
        buf.put((text+"<END>").getBytes());
        buf.flip();
	try { 
	    writer.write(buf);
	} catch (IOException ex) {}
    }
}
